package jam.network;

import jam.model.ServerModel;
 
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

//
// =============================================================================
//
    
/**
 * Does network handling and the like. Main protocol stuff.
 */
public class NetworkController { 
    private static final int SERVER_PORT = 7777;   
 
    private ServerModel model;
    private ServerSocket serverSocket;
    
    //
    // =========================================================================
    //
    
    public ServerModel getModel() { return this.model; }
    
    //
    // =========================================================================
    //
    
    /**
     * Constructor.
     */
    public NetworkController(ServerModel model) {
        this.model = model;
        
        // Try to create the socket. This opens the socket for connections
        try {
            this.serverSocket = new ServerSocket(SERVER_PORT);
        } catch (IOException e) {
            System.out.println("Cannot open socket.");
            System.exit(-1);
        }
    }
    
    /**
     * Start accepting connections. This blocks until the socket is closed.
     */
    public void listen() {
        // Loop until the socket dies, essentially.
        while (this.serverSocket.isClosed() == false) {
            // Try and setup a new user connection.
            Socket clientSocket = null;
            try {
                // This will block until a new connection has been made.
                clientSocket = this.serverSocket.accept();
                
                // Create a new network thread and launch it.
                Thread t = new ClientController(this, clientSocket);
                t.start();
            } catch (IOException e) {
                System.out.println("Failed to accept user.");
                System.exit(-1);
            }
        }
    }
}
